/**
 * create by young (young2f@outlook.com) on 2023/4/21
 * TCP服务,用于电能表上报数据，上行gw376.1协议，下行645-2007协议
 */
'use strict';
const net = require('net');
const fs = require('fs');
const moment = require('moment');
module.exports = class {
  constructor(app) {
    this.app = app;
    this.config = app.config;

  }

  async init() {
    const server = net.createServer((socket) => {
      this.logger('客户端已连接');
      // socket.setEncoding('binary');
      socket.on('data', (data) => {
        try {
          const buff = Buffer.from(data, 'utf8');
          const hexStr = buff.toString('hex');
          this.logger(hexStr);
        } catch (e) {
          console.error(e);
        }
      });

      socket.on('end', () => {
        this.logger('TCP客户端已断开连接');
      });
    });
    const port = this.config.tcpPort;
    server.listen(port, () => {
      console.log(`TCP服务监听端口：${port}`);
    });
  }

  logger(info) {
    const logFile = this.config.logsPath + '/gw3761.log';
    const time = moment()
      .format('YYYY-MM-DD HH:mm:ss');
    console.log(time + ' ' + info);
    fs.appendFile(logFile, time + '-->' + info + '\r\n', 'utf8', err => {
    });
  }
};

